package com.hondee.filemerge;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileMerge {

	public static void main(String[] args) {
		
		if(args.length!=2){return;}
		
		String settingsFileName = args[0];
		String targetFilePath = args[1];
		
		File mergeSettingFile = new File(settingsFileName);
		List<String> readyFiles = new ArrayList<>();
		if(mergeSettingFile.exists()){
			try(BufferedReader reader = new BufferedReader(new FileReader(mergeSettingFile))) {
				while(reader.ready()){
					String readLine = reader.readLine();
					if(readLine!=null && readLine.length()>0){
						readyFiles.add(readLine);
					}
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		
		if(readyFiles.size()>0){
			try(BufferedWriter targetwriter = new BufferedWriter(new FileWriter(new File(targetFilePath)))) {
				for(String fileName : readyFiles){
					File file = new File(fileName);
					if(file.exists()){
						//写注释
						targetwriter.write("/****** filename:"+file.getName()+" ******/\r\n");
						try(BufferedReader filereader = new BufferedReader(new FileReader(file))){
							while(filereader.ready()){
								String readLine = filereader.readLine();
								if(readLine.trim().startsWith("/*") && readLine.trim().endsWith("*/")){
									continue;
								}
								readLine = readLine.replace("[\\t|\\s]+", "");
								targetwriter.write(readLine);
							}
							targetwriter.write("\r\n");
						}catch (IOException e) {
							e.printStackTrace();
						}
					}
					targetwriter.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
